<template>
	<view class="login-wrapper">
		<view class="header">
			<view> 欢迎使用 云油即送 </view>
			<view class="header-title"> 云油伴您，省心无忧 </view>
		</view>
		<view class="log-btn" v-if="loginType == 1">
			<view>

				<u-button v-if="agreementFlag" type="primary" shape="circle" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">手机号一键登录</u-button>
				<u-button v-else type="primary" shape="circle" @click="agreementFlagHandler">手机号一键登录</u-button>
				<view class="text" @click="loginType = 2">验证码登录</view>
			</view>
		</view>
		<view v-else style="width: 80%;margin-top: 150rpx;">
			<view class="flex" style="border-bottom: 1px solid #ccc;">
				<text class="self-center mr10" style="border-right: 1px #CCCCCC solid; padding-right: 15rpx;">
					+86</text>
				<u-input v-model="loginData.phone" placeholder="请输入手机号" :border="false" maxlength='11' type="number" />
			</view>
			<view class="flex mt10" style="border-bottom: 1px solid #ccc;">

				<u-input v-model="loginData.code" type="number" placeholder="请输入验证码" :border="false" maxlength='6' />
				<text class="self-center" style="color: #ff4110;font-size: 13px;" @click="getCode"> {{tips}}</text>

				<!-- <up-code :seconds="seconds" ref="uCodeRef" @change="codeChange"></up-code> -->
				<!-- @end="end" @start="start" -->
				<u-verification-code :seconds="seconds" @change="codeChange" ref="uCode"></u-verification-code>
			</view>
			<view style="margin-top: 130rpx;">
				<u-button type="primary" shape="circle" @click="smsLogin">立即登录</u-button>
			</view>
			<view style="font-size: 14px;color: #909399;text-align: center;margin-top: 50rpx;" @click="loginType = 1">
				手机号一键登录</view>
		</view>
		<view class="flex xieyi">
			<u-icon custom-prefix="custom-icon" style="margin-right: 10rpx;"
				:name="agreementFlag ? 'gouxuan':'weigouxuan'" size="15" color="#FF4110"
				@click="agreementFlag = !agreementFlag"></u-icon>我已阅读并同意<navigator>《 用户协议 》
			</navigator> 和
			<navigator>《 隐私协议 》
			</navigator>
		</view>
	</view>

</template>

<script setup lang="ts">
	import { ref } from "vue"
	import { test, toast } from '@/uni_modules/uview-plus';
	import {
		useUserStore
	} from '@/store/index.js';
	import {
		storeToRefs
	} from 'pinia';

	import API from "@/api/index.js"

	const {
		userInfo
	} = storeToRefs(useUserStore());
	const userStore = useUserStore()

	const agreementFlag = ref(false);
	const agreementFlagHandler = () => {
		toast('请同意用户协议')
	}
	// https://huaweicloud.csdn.net/64eea3054165333c3076bb52.html
	const getPhoneNumber = async (event) => {
		if (event.detail.errMsg !== 'getPhoneNumber:ok') return
		uni.showToast({
			title: '登录中',
			icon: 'loading',
			mask: true
		})
		const code = event.detail.code;
		uni.login({
			async success(res) {
				const loginCode = res.code;
				const user = await API.wxLogin({
					userName: code,
					password: loginCode
				})
				const { roleId, phone, lat, lng, id, depId } = user.attach
				const { accessToken, refreshToken } = user.data
				// 存到pinia中
				userStore.$patch((state) => {
					console.log("手机一键登录state", state);
					// state.userInfo.value.name = '批量修改'
					// state.userInfo.value.type = 3
				})
			}
		})
	}
	const loginType = ref(1) // 登录方式

	/* 手机号登录 */
	const loginData = ref({
		phone: '',
		code: ''
	})

	/* 验证码 */
	const uCode = ref(null); // 验证码组件实例
	const tips = ref('获取验证码');
	const seconds = ref(60); // 倒计时

	const getCode = async () => {
		if (!test.mobile(loginData.value.phone)) {
			return toast('手机号不正确')
		}
		// if (uCode.value.canGetCode) {
		// 模拟向后端请求验证码
		uni.showLoading({
			title: '正在获取验证码'
		})
		API.getSmsCode('Verify/getSmsCode/' + loginData.value.phone + '/1', {
			phone: loginData.value.phone,
			clent: 1
		}).then(res => {
			console.log("验证码成功", res);
			uni.hideLoading();
		}).catch(res => {
			console.log("验证码失败", res);
			uni.hideLoading();
			uni.showToast({
				title: res,
				icon: 'none'
			})
		})
		// uCode.value.start();

		// }
	}

	/* 验证码登录 */
	const smsLogin = async () => {
		if (!test.mobile(loginData.value.phone)) {
			return toast('手机号不正确')
		}
		if(!agreementFlag.value){
			return toast('请先勾选协议！')
		}
		uni.showLoading({
			title:"登录中，请稍等..."
		})
		let res = await API.smsLogin({
			userName:loginData.value.phone,
			password:loginData.value.code,
			clentMsgId:'',
			platform:'0',
			userId:'',
			lan:uni.getStorageSync('location').lat,
			lng:uni.getStorageSync('location').lng,
			ipAddress:uni.getStorageSync('location').city
		});
		console.log("登录信息",res);
		uni.hideLoading()
		// 存到pinia中
		if(res){
			uni.hideLoading()
			uni.setStorageSync('userInfo',res.attach)
			userStore.$patch((state) => {
				console.log("验证码登录state", state.userInfo,state);
					state.userInfo.name = loginData.value.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
				state.userInfo.phone = loginData.value.phone
				// state.userInfo.value.type = 3
				state.token = res.data.accessToken
				state.refresh_token = res.data.refreshToken
			})
			uni.setStorageSync('accessToken', res.data.accessToken);
			uni.setStorageSync('refreshToken', res.data.refreshToken);
			uni.showToast({
				title: '登录成功',
				icon: 'loading'
			})
			setTimeout(()=>{
				uni.switchTab({
					url:'/pages/mine/mine'
				})
			},1000)
		}
	}
	const codeChange = (text : string) => {
		tips.value = text
	}
</script>

<style lang="scss">
	.login-wrapper {
		width: 100%;
		height: calc(100vh - 44px - var(--status-bar-height));
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;


		.log-btn {
			position: absolute;
			top: calc(50% - 84px);
			width: 80%;
			margin: 0 auto;

			.text {
				text-align: center;
				margin-top: 45rpx;
				color: $u-info;
				font-size: 14px;
			}
		}

		.xieyi {
			font-size: 12px;
			position: absolute;
			bottom: 50rpx;

			navigator {
				color: $u-primary;
			}
		}

	}

	.bg {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 1;
		object-fit: cover;
	}



	.content {
		width: 85%;
		margin-top: auto;
		margin-bottom: 20%;
		z-index: 11;
		text-align: center;
		font-size: 30rpx;
		color: rgba(0, 0, 0, 1);
	}

	.header {
		width: 85%;
		margin-top: 60rpx;
		font-size: 45rpx;
		font-weight: 600;
		color: rgba(0, 0, 0, 0.9);
		z-index: 11;
	}

	.header-title {
		font-size: 30rpx;
		color: rgba(0, 0, 0, 0.7);
		margin-top: 20rpx;
		font-weight: bold;
	}

	.handle {
		background-color: #5BE286;
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
		font-size: 35rpx;
		padding: 20rpx 30rpx;
		margin-bottom: 40rpx;
	}
</style>